﻿using CommonClass;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Interface;
using I_Produce.Read.API.Application.Commands.BreedingMotherCommand;
using MediatR;
using Newtonsoft.Json;

namespace I_Produce.Read.API.Application.CommandHandlers.BreedingMotherHandler
{
	public class BreedingMotherQueryCommandHandler : IRequestHandler<BreedingMotherQueryCommand, ApiResult<PagerResult<BreedingMother>>>
	{

		private readonly IBreedingMotherRepository _repository;
		private readonly Cross_services_Helper _httpClient;

		public BreedingMotherQueryCommandHandler(IBreedingMotherRepository repository, Cross_services_Helper httpClient)
		{
			_repository = repository;
			_httpClient = httpClient;
		}

		public async Task<ApiResult<PagerResult<BreedingMother>>> Handle(BreedingMotherQueryCommand request, CancellationToken cancellationToken)
		{
			var list = _repository.All().Result.Where(x => !x.IsDel);

			if (!string.IsNullOrEmpty(request.sDateOfBreeding))
			{
				list = list.Where(x => x.DateOfBreeding >= DateTime.Parse(request.sDateOfBreeding));
			}

			if (!string.IsNullOrEmpty(request.eDateOfBreeding))
			{
				list = list.Where(x => x.DateOfBreeding < DateTime.Parse(request.eDateOfBreeding).AddDays(1));
			}

			if (!string.IsNullOrEmpty(request.auricle))
			{
				list = list.Where(x => x.Auricle.Contains(request.auricle));
			}

			if (!string.IsNullOrEmpty(request.personCharge))
			{
				list = list.Where(x => x.PersonCharge.Contains(request.personCharge));
			}

			var total = list.Count();
			var page = (int)Math.Ceiling(total * 1.0 / request.pageSize);

			List<BreedingMother> breeding = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

			foreach (var item in breeding)
			{

				var surname = await _httpClient.Get("http://10.31.56.22:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=" + item.FirstWithRam);
				item.MaleBreed = JsonConvert.DeserializeObject<BreedDTO>(surname).SheepBreed;

				var spermatophore = await _httpClient.Get("http://10.31.56.22:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=" + item.Auricle);
				item.MotherVariety = JsonConvert.DeserializeObject<BreedDTO>(spermatophore).SheepBreed;

				item.LastDateOfBreeding = _repository.GetAsync(x => x.Auricle == item.Auricle).Result.Where(x => x.DateOfBreeding < item.DateOfBreeding).Select(x => x.DateOfBreeding).Max();
			}

			return new ApiResult<PagerResult<BreedingMother>>
			{
				Code = 200,
				msg = "成功",
				Data = new PagerResult<BreedingMother>
				{
					TotalCount = total,
					PageCount = page,
					Datas = breeding
				}
			};
		}
	}
}
